package com.zut.chat.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zut.chat.config.QwenConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Map;

/**
 * 通义千问AI服务
 */
@Slf4j
@Service
public class QwenAIService {

    @Autowired
    private QwenConfig qwenConfig;

    @Autowired
    private ObjectMapper objectMapper;

    private final WebClient webClient;

    public QwenAIService() {
        this.webClient = WebClient.builder()
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024))
                .build();
    }

    /**
     * 调用通义千问API获取回复
     */
    public Mono<String> getChatResponse(String userMessage) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", qwenConfig.getModel());
            requestBody.put("max_tokens", qwenConfig.getMaxTokens());

            // 构建消息列表
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是zut聊天室的AI助手，名字叫zut机器人。你要用友好、幽默的语气回答用户问题，回答要简洁明了，不超过200字。");

            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);

            requestBody.put("messages", Arrays.asList(systemMessage, userMsg));

            return webClient.post()
                    .uri(qwenConfig.getBaseUrl() + "/chat/completions")
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + qwenConfig.getApiKey())
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(String.class)
                    .timeout(Duration.ofSeconds(300000))
                    .map(this::parseResponse)
                    .onErrorReturn("抱歉，我现在有点忙，请稍后再试～");

        } catch (Exception e) {
            log.error("调用通义千问API失败", e);
            return Mono.just("抱歉，我现在有点忙，请稍后再试～");
        }
    }

    /**
     * 解析API响应
     */
    private String parseResponse(String response) {
        try {
            JsonNode jsonNode = objectMapper.readTree(response);
            JsonNode choices = jsonNode.get("choices");
            if (choices != null && choices.isArray() && choices.size() > 0) {
                JsonNode message = choices.get(0).get("message");
                if (message != null) {
                    JsonNode content = message.get("content");
                    if (content != null) {
                        return content.asText();
                    }
                }
            }

            // 如果解析失败，返回默认消息
            log.warn("解析通义千问响应失败: {}", response);
            return "抱歉，我理解不了你的问题，可以换个方式问我吗？";

        } catch (Exception e) {
            log.error("解析通义千问响应异常", e);
            return "抱歉，我现在有点忙，请稍后再试～";
        }
    }
}
